package com.zlm.controller;

import com.zlm.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
public class HelloController {

    /**
     * /admin/**   ROLE_ADMIN
     * /user/**    ROLE_USER
     * /guest/**   ROLE_USER ROLE_GUEST
     *
     * admin    ADMIN USER
     * user     USER
     * blr      Guest
     *
     * @return
     */
    @GetMapping("/admin/hello")
    public String admin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        // 得到所有的权限
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        System.out.println("用户信息：" + user.toString());
        System.out.println("权限信息：" + authorities.toString());
        return "hello admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        // 得到所有的权限
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        System.out.println("用户信息：" + user.toString());
        System.out.println("权限信息：" + authorities.toString());
        return "hello user";
    }

    @GetMapping("/guest/hello")
    public String guest() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        // 得到所有的权限
        if(user != null) {
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            System.out.println("用户信息：" + user.toString());
            System.out.println("权限信息：" + authorities.toString());
        }

        return "hello guest";
    }

    @GetMapping("/hello")
    public String hello() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            User user = (User) authentication.getPrincipal();
            // 得到所有的权限
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            System.out.println("用户信息：" + user.toString());
            System.out.println("权限信息：" + authorities.toString());
        }
        return "hello";
    }
}